﻿package com.ppb.http.util;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientUtil {

	public static String doGet(String netUrl){
			String responseBody = null;
			HttpClient httpClient = new HttpClient();		
			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			// 使用GET方法，如果服务器需要通过HTTPS连接，那只需要将下面URL中的http换成https
			System.out.println("doGet connect:" + netUrl );
			GetMethod getMethod = new GetMethod(netUrl);
			int statusCode;
			try {
				statusCode = httpClient.executeMethod(getMethod);
				if (statusCode != HttpStatus.SC_OK) {
					System.err.println("Method failed:" + getMethod.getStatusLine());
				}			
				responseBody = getMethod.getResponseBodyAsString();
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return responseBody;
		}

	public static String doPost(String netUrl, NameValuePair[] parameters){
			String responseBody = null;
			HttpClient httpClient = new HttpClient();	
			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			System.out.println(new Date()+" doPost connect:" + netUrl );
			long start = System.currentTimeMillis();
			PostMethod postMethod = new PostMethod(netUrl); 
			if(parameters!=null)
			postMethod.setRequestBody(parameters);
			int statusCode;
			try {
				statusCode = httpClient.executeMethod(postMethod);
				
				if (statusCode != HttpStatus.SC_OK) {
					System.err.println("Method failed:" + postMethod.getStatusLine());
				}			
				responseBody = postMethod.getResponseBodyAsString();
				System.out.println(System.currentTimeMillis()-start+ " ResponseBody:"+responseBody);
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return responseBody;
		}
	/**   
     * 以POST方式向指定地址发送数据包请求,并取得返回的数据包   
     *    
     * @param urlString   
     * @param requestData   
     * @param requestProperties   
     * @return 返回数据包   
     * @throws Exception   
     */    
    public static byte[] requestGet(String urlString, byte[] requestData,     
            Properties requestProperties) throws Exception {     
        byte[] responseData = null;     
    
        HttpURLConnection con = null;     
    
        try {     
            URL url = new URL(urlString);     
            con = (HttpURLConnection) url.openConnection();     
    
            if ((requestProperties != null) && (requestProperties.size() > 0)) {     
                for (Map.Entry<Object, Object> entry : requestProperties     
                        .entrySet()) {     
                    String key = String.valueOf(entry.getKey());     
                    String value = String.valueOf(entry.getValue());     
                    con.setRequestProperty(key, value);     
                }     
            }     
    
            con.setRequestMethod("GET"); // 置为POST方法     
    
            con.setDoInput(true); // 开启输入流     
            con.setDoOutput(true); // 开启输出流     
    
            // 如果请求数据不为空，输出该数据。     
            if (requestData != null) {     
                DataOutputStream dos = new DataOutputStream(con     
                        .getOutputStream());     
                dos.write(requestData);     
                dos.flush();     
                dos.close();     
            }     
    
            int length = con.getContentLength();     
            // 如果回复消息长度不为-1，读取该消息。     
            if (length != -1) {     
                DataInputStream dis = new DataInputStream(con.getInputStream());     
                responseData = new byte[length];     
                dis.readFully(responseData);     
                dis.close();     
            } else {
				System.out.println("返回数据空");
			}    
        } catch (Exception e) {     
            throw e;     
        } finally {     
            if (con != null) {     
                con.disconnect();     
                con = null;     
            }     
        }     
    
        return responseData;     
    }     
}
